package com.wc.utils;

import com.wc.constant.BMS;
import com.wc.domain.Book;
import lombok.val;

import java.io.*;
import java.math.BigDecimal;
import java.time.LocalDate;

public class FileUtil {
    /**
     * 查找图书，要求至少能够【分别】根据ISBN、书名、作者、价格区间进行查找
     *
     * @param fileName 待查询的文件
     * @param type     查询条件的类型
     * @param query    查询条件
     * @return 字符串形式的图书信息
     */
    public static String getBookInfo(String fileName, String type, String query) throws IOException {
        String res = "";
        if (type == null) {
            throw new RuntimeException("待查找的类型不能为空");
        }
        BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(fileName)));

        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            switch (type) {
                case "isbn"://{1001,java,zhangsan,youdian,888}
                case "name":
                case "auth":
                    String auth = getValueByKey(line, type);
                    if(auth.equals(query)){
                        return line;
                    }
                    break;
                case "price":
                    String priceStr = getValueByKey(line, "price");
//                    System.out.println(priceStr);
                    int price = Integer.parseInt(priceStr);
                    String[] split = query.split(","); //100,500
                    int min = Integer.parseInt(split[0]);
                    int max = Integer.parseInt(split[1]);
                    if(price >= min && price<=max){
                        res+=line+"\n";
                    }
                    break;
                default:
                    return "";
            }
        }
        return res;
    }
    /**
     * 将字符串转换为Book对象
     * @param str
     * @return
     */
    public static Book str2Book(String str){
         String isbn = getValueByKey(str, "isbn");
        String name = getValueByKey(str, "name");
        String auth = getValueByKey(str, "auth");
        String birthStr = getValueByKey(str, "birth");
        String[] split = birthStr.split("-");
        LocalDate birth = LocalDate.of(Integer.valueOf(split[0]), Integer.valueOf(split[1]), Integer.valueOf(split[2]));
        String pulisher = getValueByKey(str, "pulisher");
        String priceStr = getValueByKey(str, "price");
        int price = Integer.valueOf(priceStr);
        Book book = new Book(isbn, name, auth, birth, pulisher, new BigDecimal(price));
        return book;
    }

    /**
     * 获取每一行图书信息key对应的值
     * @param line
     * @param key
     * @return
     */
    private static String getValueByKey(String line, String key) {
        int keyIndex = line.indexOf(key);
        keyIndex += key.length() + 1;
//        System.out.println(keyIndex);
        String tmp = line.substring(keyIndex);

        if (key.equals("price")) {
            int kuoHao = tmp.indexOf(")");
//            System.out.println(douHao);
            return tmp.substring(0, kuoHao);
        } else {
            int douHao = tmp.indexOf(",");
//            System.out.println(douHao);
            return tmp.substring(0, douHao);
        }
    }

    /**
     * 在目标文件的任意位置插入内容
     * 1、将插入点之后的内容写到临时文件中
     * 2、将待插入的内容插入到插入点位置
     * 3、将临时文件中的内容追加到目标文件的结尾
     *
     * @param fileName 待插入内容的内容
     * @param pos      插入位置
     * @param content  插入内容
     * @throws IOException
     */
    public static void fileRandInsert(String fileName, int pos, String content) {
        File file = new File(fileName);
        RandomAccessFile raf = null;
        FileOutputStream fos = null;
        FileInputStream fis = null;
        try {
            raf = new RandomAccessFile(file, "rw");

            //临时文件
            File tmp = File.createTempFile("hahaha", "tmp");
            fos = new FileOutputStream(tmp);
            fis = new FileInputStream(tmp);

            raf.seek(pos);

            int len = -1;
            byte[] buf = new byte[2];
            while ((len = raf.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }
            fos.flush();

            raf.seek(pos);
            //将字符串转换成字节数组
            byte[] bytes = content.getBytes();
            raf.write(bytes);
            //将文件指针定位到追加后的位置
            raf.seek(pos + bytes.length);

            while ((len = fis.read(buf)) != -1) {
                raf.write(buf, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //释放资源
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fos != null) {
                        fos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (raf != null) {
                        try {
                            raf.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    public static void main(String[] args) throws Exception {
//        int insertPosition = 11;
//        String content = "中国人民";
//        String fileName = "abcd";
//        fileRandInsert(fileName, insertPosition, content);

        String book = getBookInfo(BMS.DB_BOOKS, "price", "100,500");
        System.out.println(book);

//        String str ="Book(isbn=147529095927, name=碧氖宠截套蹋援刻模磅, auth=费时, birth=2009-09-07, publisher=隶哆否瘩搞杯刑督筛矩, price=925)";
//        Book book = str2Book(str);
//        System.out.println(book);
    }
}
